<template>
  <div class="workflow-edit">
    <div class="header">
      <div class="header-left">
        <h2>{{ workflow.title || '工作流编辑' }}</h2>
        <el-tag>{{ workflow.type }}</el-tag>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-button @click="back">返回</el-button>
          <el-button type="primary" @click="importJson">导入JSON</el-button>
          <el-button type="primary" :loading="saving" @click="save">
            保存
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 导入JSON对话框 -->
    <el-dialog
      v-model="importDialog.visible"
      title="导入工作流"
      width="80%"
      destroy-on-close
    >
      <div class="import-dialog">
        <el-upload
          class="json-uploader"
          drag
          accept=".json"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将 JSON 文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持导入 ComfyUI 导出的 JSON 工作流文件
            </div>
          </template>
        </el-upload>

        <div v-if="importDialog.content" class="preview-json">
          <h4>预览内容</h4>
          <el-input
            v-model="importDialog.content"
            type="textarea"
            :rows="10"
            readonly
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialog.visible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!importDialog.content"
            @click="confirmImport"
          >
            确认导入
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工作流编辑器 -->
    <div class="editor-container">
      <json-node-editor
        v-model="workflow.workflow"
        @change="handleWorkflowChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { useWorkflowStore } from '@/stores/workflow'
import JsonNodeEditor from '@/components/JsonNodeEditor.vue'

const route = useRoute()
const router = useRouter()
const workflowStore = useWorkflowStore()

const saving = ref(false)
const workflow = ref({
  id: '',
  title: '',
  type: '',
  workflow: '{}',
  template: '{}'
})

// 导入对话框
const importDialog = ref({
  visible: false,
  content: ''
})

// 获取工作流数据
const getWorkflow = async () => {
  try {
    const id = route.params.id as string
    const data = await workflowStore.getWorkflow(id)
    workflow.value = data
  } catch (error) {
    console.error('Failed to get workflow:', error)
    ElMessage.error('获取工作流失败')
    router.push('/workflow')
  }
}

// 打开导入对话框
const importJson = () => {
  importDialog.value.visible = true
}

// 处理文件选择
const handleFileChange = (file: File) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const content = e.target?.result as string
      // 验证是否为有效的 JSON
      JSON.parse(content)
      importDialog.value.content = content
    } catch (error) {
      ElMessage.error('无效的 JSON 文件')
    }
  }
  reader.readAsText(file.raw)
}

// 确认导入
const confirmImport = () => {
  try {
    workflow.value.workflow = importDialog.value.content
    importDialog.value.visible = false
    ElMessage.success('导入成功')
  } catch (error) {
    ElMessage.error('导入失败')
  }
}

// 处理工作流变更
const handleWorkflowChange = (value: string) => {
  workflow.value.workflow = value
}

// 保存工作流
const save = async () => {
  try {
    saving.value = true
    await workflowStore.updateWorkflow(workflow.value.id, workflow.value)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('Failed to save workflow:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 返回列表
const back = () => {
  router.push('/workflow')
}

// 初始化
onMounted(() => {
  getWorkflow()
})
</script>

<style scoped lang="scss">
.workflow-edit {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
      }
    }
  }

  .editor-container {
    flex: 1;
    background: #1e1e1e;
    border-radius: 8px;
    overflow: hidden;
  }

  .import-dialog {
    .json-uploader {
      width: 100%;
      margin-bottom: 20px;
    }

    .preview-json {
      h4 {
        margin: 0 0 12px;
        color: #666;
      }
    }
  }
}
</style> 